package cn.itsource.mq;

import cn.itsource.constants.Constants;
import cn.itsource.pojo.bo.PayOrderBo;
import cn.itsource.pojo.domain.Order;
import cn.itsource.service.IOrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.util.Objects;

//：事务监听器
@Slf4j
@RocketMQTransactionListener(txProducerGroup = "service-order")
public class CourserOrderTransactionListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IOrderService orderService;

  
    //执行本地事务的方法
    //msg: 消息对象 ：
    //arg : 扩展参数
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        Order order = (Order) arg;
        try {
            orderService.updateById(order);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    //检查本地事务的方法
    //msg：消息对象
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        PayOrderBo payOrderBo = (PayOrderBo) msg.getPayload();
        String orderNo = payOrderBo.getOrder_no();
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderNo));
        if (order == null) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        if (!Objects.equals(order.getStatus(), Constants.Order.UNPAID)){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //判断本地事务是否执行成功，就是去数据库查询是否有 executeLocalTransaction 方法执行之后的结果
        return RocketMQLocalTransactionState.COMMIT;
    }
}